# coding=utf-8
"""
    @project: qabot
    
    @file： user.py
    @date：2023/9/4 10:57
    @desc:
"""
from django.core import cache
from application.serializers.application_serializers import ApplicationSerializer
from drf_yasg.utils import swagger_auto_schema
from rest_framework.decorators import action, permission_classes

from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from rest_framework.views import Request
from common.response import result
from common.util import common as util
from django.utils.translation import gettext_lazy as _
from application.swagger_api.application_api import ApplicationApi

from xpack.serializers.auth_config_serializer import AuthConfigSerializer
from xpack.serializers.auth_config_serializer import AuthLoginSerializer
from common.auth import TokenAuth, has_permissions

user_cache = cache.caches['user_cache']
token_cache = cache.caches['token_cache']

class Detail(APIView):
    @action(methods=["GET"], detail=False)
    @swagger_auto_schema(operation_summary=_("Get embedded js"),
                            operation_id=_("Get embedded js"),
                            tags=[_("Application")],
                            manual_parameters=ApplicationApi.ApiKey.get_request_params_api())
    def get(self, request: Request, auth_type: str):
        where = {
            'platform': auth_type
        }
        data = {
            'id': '',
            'auth_type': auth_type,
            'is_active': True,
            'config_data': {}
        }
        info = AuthConfigSerializer.Query(data = where).info()
        if info is not None:
            data['config_data'] = info.config
            data['id'] = info.id
            data['is_active'] = info.is_active
        return result.success(data=data)
    class Operate(APIView):
        authentication_classes = [TokenAuth]
        @action(methods=["PUT"], detail=False)
        def put(self, request: Request, auth_type: str):
            data = {
                "user_id": request.user.id,
                "platform": auth_type,
                "content": request.data.get('config_data'),
                "isActive": request.data.get('is_active'),
                "isValid": True
            }
            AuthConfigSerializer.Create(data = data).save()
            return result.success(data=data)
class Source(APIView):
    class List(APIView):
        @action(methods=['GET'], detail=False)
        @permission_classes((AllowAny,))
        def get(self, request: Request):
            where = {}
            list = AuthConfigSerializer.Source(data = where).list()
            res = []
            for item in list.data:
                config = item['config']
                if item['platform'] == 'wecom':
                    item['config'] = {
                        "corp_id": config['corp_id'],
                        "agent_id": config['agent_id']
                    }
                res.append(item)
            return result.success(data=res)
    class Operate(APIView):
        authentication_classes = [TokenAuth]
        @action(methods=['GET'], detail=False)
        @permission_classes((AllowAny,))
        def get(self, request: Request):
            where = {}
            list = AuthConfigSerializer.Source(data = where).list()
            return result.success(data=list.data)
        @action(methods=['POST'], detail=False)
        def post(self, request: Request):
            
            data = {
                "user_id": request.user.id,
                "platform": request.data.get('key'),
                "content": request.data.get('config'),
                "isActive": request.data.get('isActive'),
                "isValid": True,
            }
            AuthConfigSerializer.Create(data = data).save()
            return result.success(data=data)
        
        @action(methods=['PUT'], detail=False)
        def put(self, request: Request):
            data = {
                "user_id": request.user.id,
                "platform": request.data.get('key'),
                "content": request.data.get('config'),
                "isActive": request.data.get('isActive'),
                "isValid": True,
            }
            return result.success(data=data)
class Auth(APIView):
    class wecom(APIView):

        @action(methods=['GET'], detail=False)
        @permission_classes((AllowAny,))
        def get(self, request: Request):
            code = request.GET.get('code')
            res = AuthLoginSerializer.Wecom(data={'code':code}).info()
            return result.success(data=res['token'])
    class dingtalk(APIView):
        @action(methods=['GET'], detail=False)
        @permission_classes((AllowAny,))
        def get(self, request: Request):
            code = request.GET.get('code')
            res = AuthLoginSerializer.Dingtalk(data={'code':code}).info()
            return result.success(data=res['token'])
        